#include "stdafx.h"
#include "httpconnection.h"

#include <QTcpSocket>
#include <QtCore>

HttpConnection::HttpConnection(QTcpSocket* socket)
:inSocket(socket), outSocket(0)
{
	inSocket->setParent(this);
	connect(inSocket, SIGNAL(readyRead()), SLOT(onRequestData()));
	connect(inSocket, SIGNAL(disconnected()), SLOT(onConnectionClose()));
}

HttpConnection::~HttpConnection(void)
{
}

void HttpConnection::onRequestData()
{
	request.append(inSocket->readAll());
	if(request.endsWith("\r\n\r\n"))
	{
		ui->Request->setPlainText(request);
				
		//QStringList headers(request.split("\r\n",QString::SkipEmptyParts));
		//QRegExp regExp("^(?:GET|POST) (\S+) HTTP");
		//address=headers[0].section(' ', 1, 1);

		address=request.section(' ', 1, 1);

		//if(address[0]=='/')
		//{
		//	QRegExp reHost("^Host: (\S+)");
		//	reHost.indexIn(request);
		//	address+=reHost.cap();
		//}

		//ui->Response->setPlainText(address.toString());

		if(!outSocket)
		{
			outSocket=new QTcpSocket;
			outSocket->setParent(this);
			connect(outSocket, SIGNAL(readyRead()), SLOT(onResponseData()));
			connect(outSocket, SIGNAL(disconnected()), SLOT(onConnectionClose()));
			outSocket->connectToHost(address.host(), address.port(80));
		}
		outSocket->write(request.toLocal8Bit());
		outSocket->flush();
	}
}

void HttpConnection::onResponseData()
{
	QByteArray a=outSocket->readAll();
	inSocket->write(a);
	QTextCodec* codec=QTextCodec::codecForHtml(a);
	response.append(codec->toUnicode(a));
	ui->Response->setPlainText(response);
}

void HttpConnection::onConnectionClose()
{
	QStringList captionList; 
	captionList << (address.toString()) << QTime::currentTime().toString();
	ui->ConnectionsList->addTopLevelItem(new QTreeWidgetItem(captionList));
	disconnect(inSocket, SIGNAL(disconnected()), this, SLOT(onConnectionClose()));
	disconnect(outSocket, SIGNAL(disconnected()), this, SLOT(onConnectionClose()));
	inSocket->disconnectFromHost();
	outSocket->disconnectFromHost();
	inSocket->deleteLater();
	outSocket->deleteLater();
	inSocket=outSocket=0;
}
